package com.cloudkinto.service.fbaproduct;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.dao.FileDao;
import com.cloudkinto.entity.FileDo;
import com.cloudkinto.service.product.vo.FbaProductInfoExcelImport;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

/**
 * @author: xjp
 * @description:
 * @create: 2021-03-18 09:55
 **/
@Component
public class ImportExcelUtil {
    private static Logger log = Logger.getLogger(String.valueOf(ImportExcelUtil.class));

    private final static String excel2003L = ".xls"; // 2003- 版本的excel
    private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel

    @Autowired
    private FileDao fileDao;
    /**
     * 将流中的Excel数据转成List<Map>
     *
     * @param in       输入流
     * @param fileName 文件名（判断Excel版本）
     * @return
     * @throws Exception
     */
    public List<Object> parseExcel(InputStream in, String fileName,List<CustomizedColumnVO> customizedColumn) throws Exception {
        // 根据文件名来创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        XSSFSheet sheet=null;
        Row row = null;
        Cell cell = null;
        // 返回数据
        List<FbaProductInfoExcelImport> allList = new ArrayList<>();
        List<Object> list=new ArrayList<>();
        Map<String,List<FileDo>> keyList=new HashMap<>();
        Class<?> salaryArchivesClass = EasyPoiDynamicGenerationClassUtil.generatePrototypeClass(customizedColumn);
        // 遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = (XSSFSheet)work.getSheetAt(i);
//            keyList = uploadPerson(sheet);
            if (sheet == null) {
                continue;
            }
            // 取第一行标题
            row = sheet.getRow(0);
            String title[] = null;
            if (row != null) {
                title = new String[row.getLastCellNum()];
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    title[y] = (String) getCellValue(cell);
                }
            } else {
                continue;
            }
            // 遍历当前sheet中的所有行
            for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
                row = sheet.getRow(j);
                if (!getCellValue(row.getCell(0)).equals("")) {
                    Object o = salaryArchivesClass.newInstance();
                    // 遍历所有的列
                    for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                        cell = row.getCell(y);
                        if(cell != null){
                            for(int ii=0;ii<customizedColumn.size();ii++){
                                String[] keyo=new String[1];
                                if (/*title[y]*/y == Integer.parseInt(customizedColumn.get(ii).getTitleName())){
                                    Field declaredField = o.getClass().getDeclaredField(customizedColumn.get(ii).getColumnName());
                                    declaredField.setAccessible(true);
                                    String cellValue = getCellValue(cell);
                                    if(StringUtils.isNotEmpty(cellValue)){
                                        declaredField.set(o,cellValue);
                                    }
//                                    if("productPictureFileId".equals(declaredField.getName())){
//                                        keyo[0]=j+"-"+y;
//                                        keyList.forEach((key,value)->{
//                                            if(key.equals(keyo[0])){
//                                                try {
//                                                    declaredField.set(o,value.get(0).getId().toString());
//                                                } catch (IllegalAccessException e) {
//                                                    e.printStackTrace();
//                                                }
//                                            }
//                                        });
//                                    }
                                    break;
                                }
                            }
                        }
                    }
                    list.add(o);
                }
            }
        }
        work.close();
        return list;
    }

    public Map<String,List<FileDo>> uploadPerson(XSSFSheet sheetAt) throws Exception {
        XSSFDrawing drawingPatriarch = sheetAt.getDrawingPatriarch();
        List<XSSFShape> shapes = drawingPatriarch.getShapes();
        Map<String,List<FileDo>> map = new HashMap<>();
        for(int i=0;i<shapes.size();i++){
            XSSFShape shape = shapes.get(i);
            XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
            if(shape instanceof XSSFPicture){
                List<FileDo> list = new ArrayList<>();
                int row1 = anchor.getRow1();
                int col1 = anchor.getCol1();
                String key = row1 + "-" + col1 ;
                FileDo fileDo = new FileDo();
                fileDo.setCreateTime(new Date());
                fileDo.setDeleteFlag(0);
                fileDo.setFileName(key+"-"+i);
                fileDo.setFileSuffix("png");
                fileDao.insert(fileDo);
                list.add(fileDo);
                List<FileDo> fileDos = map.get(key);
                if(CollectionUtils.isEmpty(fileDos)){
                    map.put(key,list);
                }else {
                    fileDos.add(fileDo);
                }
            }
        }
        return map;
    }

    public static void savePic(String i, PictureData pic) throws Exception {
        byte[] data = pic.getData();
        String path="C:\\excel\\";
        File file=new File(path);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        FileOutputStream out = new FileOutputStream(path + i + ".png");
        out.write(data);
        out.close();
    }
    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr ,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr); // 2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr); // 2007+
        } else {
            throw new Exception(SysConstant.File_AnalysisForm_Error);//解析的文件格式有误！
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
        String value = null;
        DecimalFormat df = new DecimalFormat("#.0"); // 格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DecimalFormat df2 = new DecimalFormat("0"); // 格式化数字
        switch (cell.getCellType().name()) {
            case "STRING":
                value = cell.getRichStringCellValue().getString();
                break;
            case "NUMERIC":
                String dataFormatString = cell.getCellStyle().getDataFormatString();
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else if("0.00_);[Red]\\(0.00\\)".equals(cell.getCellStyle().getDataFormatString())){
                    value = df.format(cell.getNumericCellValue());
                }else{
                    //Sun Dec 31 15:03:00 CST 1899格式化时间15:03
                    value = sdf2.format(cell.getDateCellValue()).substring(11, 16);
                }
                break;
            case "BOOLEAN":
                //value = cell.getBooleanCellValue();
                value = "";
                break;
            case "BLANK":
                value = "";
                break;
            default:
                break;
        }
        return value;
    }

    public static List<String> getExcelTitle(InputStream in, String fileName) throws Exception {
        // 根据文件名来创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        // 返回数据
        Map<String,List<String>> map = new HashMap<>();
        // 取Excel中的sheet
        List<String> list=new ArrayList<>();
        sheet = work.getSheetAt(0);
        if (null != sheet) {
            // 取第一行标题
            row = sheet.getRow(0);
            if (null != row) {
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    if(StringUtils.isNotEmpty((String) getCellValue(cell))){
                        list.add((String) getCellValue(cell));
                    }
                }
            }
        }
        work.close();
        return list;
    }
}